package cn.lxh.ymcc.mq.listener;

import cn.lxh.ymcc.domain.PayOrder;
import cn.lxh.ymcc.dto.PayNotifyDto;
import cn.lxh.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(
        txProducerGroup = "service-pay-tx-group"
)
@Slf4j
public class PayNotifyRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;

    /**
     * 执行本地事务
     *   需要在此方法中保存主订单和子订单
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //保存本地事务  修改支付宝的状态和时间
        log.info("执行本事务，修改支付单的支付状态");
        PayOrder payOrder = (PayOrder) arg;
        PayOrder orderTmp = payOrderService.selectByOrderNo(payOrder.getOrderNo());
//        @TODO 包装类的使用
        if(!orderTmp.getPayStatus().equals(PayOrder.STATE_WAIT_PAY)){//状态不对，不做修改
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        payOrderService.updateById(payOrder);
        return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
    }

    /**
     * 检查本地事务
     *   检查本地的支付单状态是否是已支付
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("检查支付单的支付状态。。");
        try {
            byte[] bodyTmp = (byte[]) message.getPayload();
            String notifyDtoStr = new String(bodyTmp, StandardCharsets.UTF_8);
            PayNotifyDto dto = JSONObject.parseObject(notifyDtoStr, PayNotifyDto.class);
            if(dto != null){
                return RocketMQLocalTransactionState.UNKNOWN;//未知
            }
            PayOrder orderTmp = payOrderService.selectByOrderNo(dto.getOrderNo());
            if(orderTmp == null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            //判断支付单的状态是否是已支付
            if(orderTmp.getPayStatus().equals(PayOrder.STATE_PAY_SUCCESS)){
                return RocketMQLocalTransactionState.COMMIT;//才真正的发送事务消息成功
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}